<template>
  <div class="app-container">
    <Upload-excel
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import { importEmployee } from '@/api/employee'
import { formatExcelDate } from '@/utils/index'
export default {
  name: 'Import',
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 发送请求
    async doExcel(data) {
      try {
        const res = await importEmployee(data)
        this.$message.success(res.message)
        // 回退到原先的页面
        this.$router.back()
        console.log(res)
      } catch (err) {
        console.log(err)
        this.$message.error(err)
      }
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // 1.读取excel表格转化为行和列的数据
      // 2.将数据安装接口文档进行格式化转化, 将中文的键转化为英文
      const data = this.transExcel(results)
      console.log(data)
      // 3. 发请求,实现数据的批量导入
      this.doExcel(data)
    },
    transExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'

      }
      return data.map(zhObj => {
        const zhKeys = Object.keys(zhObj)
        console.log(zhKeys) // ['入职日期', '姓名', '工号', '手机号', '转正日期', '部门']
        const enObj = {}
        zhKeys.forEach(zhKey => {
          // const enKey = mapInfo[zhKey]
          // console.log(enKey)
          // enObj[enKey] = data[zhKey]
          if (mapInfo[zhKey] === 'timeOfEntry' || mapInfo[zhKey] === 'correctionTime') {
            enObj[mapInfo[zhKey]] = new Date(formatExcelDate(zhObj[zhKey])) // 1.时间转换 2345=> 2022-6-26 // 2.new Date()
          } else {
            enObj[mapInfo[zhKey]] = zhObj[zhKey]
          }
        })
        return enObj
      })
    }

  }
}
</script>

